package br.com.affero.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import br.com.affero.bean.Document;
import br.com.affero.facade.DomainFacade;
import br.com.affero.form.DocumentForm;
import br.com.affero.util.UploadedFile;

public class EditDocumentAction extends Action {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
	
		if (request.getMethod().equalsIgnoreCase("post")) {
			if (form instanceof DocumentForm) {
				DocumentForm documentForm = (DocumentForm) form;
				Document document = DomainFacade.getInstance().getDocument(documentForm.getId());
				
				BeanUtils.copyProperties(document, documentForm);
				String filePath = UploadedFile.save(getServlet().getServletContext(), documentForm.getFile(), "documents");
				if (filePath != null) {
					document.setFilePath(filePath);
				}
				
				DomainFacade.getInstance().updateDocument(document);
				
				return mapping.findForward("list");
			}
			
			return null;
		}
		
		Integer id = Integer.parseInt(request.getParameter("id"));
		request.setAttribute("document", DomainFacade.getInstance().getDocument(id));
		
		return mapping.findForward("formEdit");
	}
	
}
